package com.niu.wm.web.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.niu.wm.model.Customer;
import com.niu.wm.core.ResponseObject;
import com.niu.wm.form.CustomerSearchForm;
import com.niu.wm.vo.CustomerVO;
import com.niu.wm.model.User;
import com.niu.wm.service.CustomerService;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController extends BaseController{
	@Autowired
	private CustomerService customerService;
	
	/**
	 * 客户管理
	 * @return
	 */
	@RequestMapping(value = "/listCust.do")
    public String listCust(ModelMap model){
		User user = this.getCurrentUser();
		/*
		model.addAttribute("countryList", countryService.loadAll() );
		model.addAttribute("xlList", dictService.loadChildren("xl") );
		model.addAttribute("gradeList", dictService.loadChildren("grade") );
		model.addAttribute("companyList", unitService.getAllCompany() );
		model.addAttribute("levelList", dictService.loadChildren("stulevel") );
		
		model.addAttribute("canExport", canExport(user) );
		*/
		
		return "cust/listCust";
	}
	
	/**
	 * 列出客户信息
	 * @return
	 */
	@RequestMapping(value = "/listData.do")
    @ResponseBody
    public Map<String, Object> listData(HttpServletRequest req,CustomerSearchForm form, Pageable pager){
		User user = this.getCurrentUser();
		
		pager = this.convertPager(req, pager);
		Map<String,Object> map = new java.util.HashMap<String, Object>();
		
		int total = customerService.countCustomer(form);
		List<CustomerVO> ls = customerService.queryCustomer(form, pager);
				
		map.put("total", total);
		map.put("rows", ls);
		
		return map;
	}
	
	/**
	 * 导入客户信息--界面
	 * @return
	 */
	@RequestMapping(value = "/export.do")
    @ResponseBody
    public void exportProduct(HttpServletRequest request, HttpServletResponse response, CustomerSearchForm form){
		User user = this.getCurrentUser();
		Pageable pager = null;
		
		//fld-code-->fld-title
		List<String[]> lsFld = new ArrayList<String[]>();
		//List< Map(fld-code, fld-value)>
		List<Map<String,Object>> lsRows = new ArrayList<Map<String,Object>>();
			
		lsFld.add( new String[]{"name","客户名称"} );
		lsFld.add( new String[]{"email","Email"} );
		lsFld.add( new String[]{"lxr","联系人"} );
		lsFld.add( new String[]{"website","公司网址"} );
		lsFld.add( new String[]{"fax","公司传真"} );
		lsFld.add( new String[]{"addr","公司地址"} );
		lsFld.add( new String[]{"country","所在国家"} );
		lsFld.add( new String[]{"product","经营产品"} );
		lsFld.add( new String[]{"cust_from","客户资料来源"} );
		lsFld.add( new String[]{"level","客户等级"} );
		lsFld.add( new String[]{"memo1", "备注1"} );
		lsFld.add( new String[]{"memo2", "备注1"} );
		lsFld.add( new String[]{"memo3", "备注1"} );
		
		
		pager = new PageRequest(0, 50000);
		
		List<CustomerVO> ls = customerService.queryCustomer(form, pager);
		
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = null;
		HSSFRow row = null;
		HSSFCell cell = null;
		
		// 创建Excel工作簿的第一个Sheet页
		sheet = workbook.createSheet("sheet1");
		
		int rowNo =0;
		row = sheet.createRow(rowNo ++); 

		for(int i=0; i < lsFld.size(); i++){
			String[] pair = lsFld.get(i);
			
			cell = row.createCell(i); 
			cell.setCellType(CellType.STRING);
			cell.setCellValue(new HSSFRichTextString(pair[1]));
		}
		
		for(CustomerVO vo:ls){
			Map<String,Object> mapVal = new HashMap<String,Object>();
			lsRows.add(mapVal);
					
			mapVal.put("name", vo.getName() );
			mapVal.put("email", vo.getEmail() );
			mapVal.put("lxr", vo.getLxr() );
			mapVal.put("website", vo.getWebsite() );
			mapVal.put("fax", vo.getFax() );
			mapVal.put("addr", vo.getAddr() );
			mapVal.put("country", vo.getCountry() );
			mapVal.put("product", vo.getProduct() );
			
			mapVal.put("cust_from", vo.getCustFrom() );
			mapVal.put("memo1", vo.getMemo1() );
			mapVal.put("memo2", vo.getMemo2() );
			mapVal.put("memo3", vo.getMemo3() );
		}
		
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
		for(Map<String,Object> rowVal: lsRows){
			row = sheet.createRow(rowNo ++);
			
			for(int i=0; i < lsFld.size(); i++){
				String fldCode = lsFld.get(i)[0];
				
				cell = row.createCell(i); 
				
				Object valueObj = rowVal.get(fldCode);
				if(valueObj instanceof Integer){
					Integer value = (Integer)valueObj;
					cell.setCellType(CellType.NUMERIC);
					if(value != null)
						cell.setCellValue(value.intValue());
				} else if(valueObj instanceof Long){
					Long value = (Long)valueObj;
					cell.setCellType(CellType.NUMERIC);
					if(value != null)
						cell.setCellValue(value.longValue());
				} else if(valueObj instanceof BigDecimal){
					BigDecimal value = (BigDecimal)valueObj;
					cell.setCellType(CellType.NUMERIC);
					if(value != null)
						cell.setCellValue(value.doubleValue());
				} else if(valueObj instanceof java.util.Date){
					java.util.Date value = (java.util.Date)valueObj;
					cell.setCellType(CellType.STRING);
					if(value != null)
						cell.setCellValue(sdf.format(value));
				}else{
					cell.setCellType(CellType.STRING);
					if(valueObj == null)
						cell.setCellValue(new HSSFRichTextString(""));
					else
						cell.setCellValue(new HSSFRichTextString(valueObj.toString()));
				}
			}
		}
		
		sdf = new SimpleDateFormat("yyyy-MM-dd");				
		String fileName = "客户导出" + sdf.format(new java.util.Date()) + ".xls";		
		try{
			fileName = new String(fileName.getBytes("utf-8"),"iso8859-1");
			
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ fileName + "\"");
			response.setContentType("application/octet-stream; charset=UTF-8");
			
			java.io.OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.flush();
			os.close();
			
			workbook.close();
		}catch(Exception e){
			logger.error("", e);
		}
	}
	
	/**
	 * 客户信息录入表格
	 * @return
	 */
	@RequestMapping(value = "/add.do")
    public String add(ModelMap model){
		Customer customer = new Customer();
		model.put("customer", customer);
		
		return "cust/customer";
	}
	
	/**
	 * 客户信息录入表格
	 * @return
	 */
	@RequestMapping(value = "/edit.do")
    public String edit(Long id, ModelMap model){
		Customer customer = customerService.load(id);
		model.put("customer", customer);
		
		return "cust/customer";
	}
	
	/**
	 * 保存客户信息到数据库
	 * @return
	 */
	@RequestMapping(value = "/save.do")
    @ResponseBody
    public ResponseObject<Customer> save(Customer customer){
		User user = this.getCurrentUser();
		try{
			if(customer.getId() == null)
				customerService.insert(user, customer);
			else
				customerService.update(user, customer);
		}catch(Exception e){
			logger.error("", e);
		}
		
		
		return new ResponseObject<Customer>(customer);
	}
	
	/**
	 * 删除商品信息
	 * @return
	 */
	@RequestMapping(value = "/delete.do")
    @ResponseBody
    public ResponseObject<Integer> delete(Long id){
		User user = this.getCurrentUser();
		
		int count = 0;
		count = customerService.delete(user, id);
		
		return new ResponseObject<Integer>(count);
	}
}
